module Painter
  require 'RMagick'
  
  class DrawElem
    class Point
      attr_reader :x, :y

      def initialize(hash)
        @x = hash['x']
        @y = hash['y']
      end
    end

    def initialize(hash)
      @controls = ['paintBrush', 'paintPencil', 'paintBrush', 'paintRect', 'paintCircle']
      @action = hash['a']
      @color = hash['c']
      @fillColor = hash['c']
      @width = hash['w']
      @filled = hash['f']
      @points = []
      hash['p'].each do |point|
        @points << Point.new(point)
      end
    end

    def paint(gc)
      gc.stroke_width(@width)
      gc.stroke = @color
      if (@filled)
        gc.fill = @color
      else
        gc.fill = 'none'
      end

  		i = 0
  		while i < @points.size - 1
        eval "#{@controls[@action]}(gc, @points[i], @points[i+1])"
  			i += 1
  		end
    end

    def paintBrush(gc, from, to)
  		gc.line(from.x, from.y, to.x, to.y)
    end

    def paintPencil(gc, from, to)
      gc.stroke_linecap('round')
      paintBrush(gc, from, to)
    end

    def paintRect(gc, from, to)
  		gc.rectangle(from.x, from.y, to.x, to.y);
    end

    def paintCircle(gc, from, to)
  		centerX = [from.x, to.x].max - ((from.x - to.x)*0.5).abs;
  		centerY = [from.y, to.y].max - ((from.y - to.y)*0.5).abs;
      len2 = (from.x - to.x)*(from.x - to.x) + (from.y - to.y)*(from.y - to.y)
  		distance = Math.sqrt(len2);
  		gc.circle(centerX, centerY, to.x, to.y);
    end
  end
end
